package com.GPT.controller;

import com.GPT.service.UserService;
import com.GPT.service.WebSocketServer;
import com.GPT.service.iface.IWeixinService;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/oauth")
public class  OauthController {
    private Logger logger = LogManager.getLogger(getClass());

    @Autowired
    private IWeixinService weixinService;

    @Value("${weixin.open.connect}")
    private String connectUrl;

    @Autowired
    private UserService userService;

    @Autowired
    private final WebSocketServer webSocketServer;

    public OauthController(WebSocketServer webSocketServer) {
        this.webSocketServer = webSocketServer;
    }

    /**
     * 跳转到微信页面
     * @param response
     * @return
     */
    @GetMapping("/weixin/login")
    @ResponseBody
    public void index(HttpServletResponse response){
        try {
            logger.info(String.format("connectUrl --> %s", connectUrl));

            // 设置响应的内容类型为图片
            response.setContentType("image/png");

            // 生成二维码
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = qrCodeWriter.encode(connectUrl, BarcodeFormat.QR_CODE, 250, 250, hints);

            // 将二维码写入响应输出流
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
        } catch (IOException | WriterException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取微信用户信息
     * @param code
     * @return
     */
    @GetMapping("/weixin/userInfo")
    @ResponseBody
    public String getWeixinUserInfo(@RequestParam(value = "code") String code) {
        System.out.println("收到的 code: " + code);
        JSONObject userInfo = weixinService.getUserInfo(code);
        webSocketServer.sendToAllClient(userInfo.toJSONString());
        System.out.println(userInfo.toJSONString());
        return "登录成功";
        /*JSONObject userInfo = weixinService.getUserInfo(code);
        webSocketServer.sendToAllClient("loginSuccess");
        System.out.println(userInfo.toJSONString());
        String message = "登录成功";
        return message;*/

        /*if (userInfo != null && userInfo.getString("openid") != null) {
            // 将用户信息保存到数据库
            try {
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(Result.build().content(userInfo));
            } catch (Exception e) {
                // 记录错误并返回服务器错误响应
                logger.error("保存用户信息到数据库失败", e);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Result.buildError("保存用户信息失败"));
            }
        } else {
            return ResponseEntity.badRequest().body(Result.buildError("获取用户信息失败"));
        }*/
    }
}
